// 数据处理页面的主要逻辑
class DataProcessing {
    constructor() {
        this.currentStep = 'upload';
        this.uploadedFileId = null;
        this.conversionTaskId = null;
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.setupFileUpload();
        this.showStep('upload');
    }

    setupEventListeners() {
        // 文件输入监听
        const fileInput = document.getElementById('fileInput');
        if (fileInput) {
            fileInput.addEventListener('change', (e) => {
                console.log('文件输入框变化事件触发');
                this.handleFileSelect(e.target.files[0]);
            });
        }

        // 转换类型选择监听
        document.getElementById('conversionType').addEventListener('change', () => {
            this.updateUploadButton();
        });

        // 上传按钮监听
        document.getElementById('uploadBtn').addEventListener('click', () => {
            this.handleUploadClick();
        });

        // 开始转换按钮监听
        document.getElementById('startConversion').addEventListener('click', () => {
            this.startConversion();
        });

        // 数据拆分模态框确认按钮监听
        document.getElementById('confirmSplitBtn').addEventListener('click', () => {
            this.confirmDataSplit();
        });
    }

    setupFileUpload() {
        this.updateUploadButton();
    }

    handleFileSelect(file) {
        if (!file) return;

        // 验证文件类型 - 仅支持xlsx格式
        const allowedTypes = [
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // xlsx
        ];

        if (!allowedTypes.includes(file.type)) {
            this.showAlert('error', '不支持的文件格式，请选择Excel文件(.xlsx)');
            return;
        }

        // 验证文件大小 (100MB)
        if (file.size > 100 * 1024 * 1024) {
            this.showAlert('error', '文件大小不能超过100MB');
            return;
        }

        // 显示文件信息
        document.getElementById('file-name').textContent = file.name;
        document.getElementById('file-size').textContent = this.formatFileSize(file.size);
        document.getElementById('file-info').classList.remove('d-none');
        
        this.selectedFile = file;
        this.updateUploadButton();
    }

    clearFile() {
        this.selectedFile = null;
        document.getElementById('file-info').classList.add('d-none');
        document.getElementById('fileInput').value = '';
        this.updateUploadButton();
    }

    updateUploadButton() {
        // 始终保持按钮可点击，在点击时进行验证和提示
        const uploadBtn = document.getElementById('uploadBtn');
        uploadBtn.disabled = false;
        
        const hasFile = !!this.selectedFile;
        const hasType = !!document.getElementById('conversionType').value;
        
        // 更新按钮文本和样式来反映状态
        if (hasFile && hasType) {
            uploadBtn.innerHTML = '<i class="fas fa-upload me-2"></i>开始上传';
            uploadBtn.className = 'btn btn-primary';
        } else {
            uploadBtn.innerHTML = '<i class="fas fa-upload me-2"></i>开始上传';
            uploadBtn.className = 'btn btn-outline-primary';
        }
    }

    handleUploadClick() {
        // 验证是否选择了文件
        if (!this.selectedFile) {
            this.showAlert('error', '请选择要上传的Excel表格文件', 'center');
            return;
        }

        // 验证是否选择了转换类型
        const conversionType = document.getElementById('conversionType').value;
        if (!conversionType) {
            this.showAlert('error', '请选择转换类型');
            return;
        }

        // 如果是数据拆分，显示模态框
        if (conversionType === 'data-split') {
            this.showDataSplitModal();
        } else {
            // 其他类型直接上传
            this.uploadFile();
        }
    }

    showDataSplitModal() {
        // 重置默认值
        document.getElementById('splitCount').value = 500;
        
        // 显示模态框 - Bootstrap 5 标准方式
        const modalElement = document.getElementById('dataSplitModal');
        const modal = new bootstrap.Modal(modalElement, {
            backdrop: 'static',
            keyboard: false
        });
        modal.show();
    }

    confirmDataSplit() {
        // 获取拆分条数
        const splitCount = parseInt(document.getElementById('splitCount').value);
        
        // 验证输入
        if (!splitCount || splitCount < 1 || splitCount > 10000) {
            this.showAlert('error', '请输入有效的拆分条数（1-10000）');
            return;
        }

        // 保存拆分条数
        this.splitCount = splitCount;
        
        // 关闭模态框 - Bootstrap 5 标准方式
        const modalElement = document.getElementById('dataSplitModal');
        const modal = bootstrap.Modal.getInstance(modalElement);
        if (modal) {
            modal.hide();
        }
        
        // 开始上传
        this.uploadFile();
    }

    async uploadFile() {
        if (!this.selectedFile) {
            this.showAlert('error', '请选择要上传的Excel表格文件', 'center');
            return;
        }

        // 验证是否选择了转换类型
        const conversionType = document.getElementById('conversionType').value;
        if (!conversionType) {
            this.showAlert('error', '请选择转换类型');
            return;
        }

        const formData = new FormData();
        formData.append('file', this.selectedFile);
        formData.append('conversionType', conversionType);
        
        // 如果是数据拆分，添加拆分条数参数
        if (conversionType === 'data-split' && this.splitCount) {
            formData.append('splitCount', this.splitCount.toString());
        }

        try {
            this.showUploadProgress(true);
            
            const response = await axios.post('/api/fileupload/single', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                onUploadProgress: (progressEvent) => {
                    const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                    this.updateUploadProgress(progress);
                }
            });

            if (response.data.success) {
                this.uploadedFileId = response.data.fileId;
                this.showAlert('success', '文件上传成功，正在开始转换...');
                
                // 切换到转换步骤并自动开始转换
                this.showStep('convert');
                this.updateConversionInfo();
                
                // 自动开始转换
                setTimeout(() => {
                    this.startConversion();
                }, 500);
            } else {
                this.showAlert('error', response.data.message || '文件上传失败');
            }

        } catch (error) {
            console.error('上传失败:', error);
            let errorMessage = '文件上传失败';
            if (error.response?.data?.message) {
                errorMessage += '：' + error.response.data.message;
            } else if (error.message) {
                errorMessage += '：' + error.message;
            }
            this.showAlert('error', errorMessage);
        } finally {
            this.showUploadProgress(false);
        }
    }

    showUploadProgress(show) {
        const progressDiv = document.getElementById('upload-progress');
        if (show) {
            progressDiv.classList.remove('d-none');
        } else {
            progressDiv.classList.add('d-none');
        }
    }

    updateUploadProgress(progress) {
        const progressBar = document.querySelector('#upload-progress .progress-bar');
        progressBar.style.width = progress + '%';
        progressBar.textContent = progress + '%';
    }

    async startConversion() {
        if (!this.uploadedFileId) return;

        try {
            const conversionData = {
                fileId: this.uploadedFileId,
                conversionType: document.getElementById('conversionType').value,
                businessRules: {
                    '厂家为空填无': { enabled: true }
                }
            };

            this.showConversionProgress(true);
            this.addLog('info', '开始数据转换...');

            const response = await axios.post('/api/dataconversion/start', conversionData);
            
            if (response.data.success) {
                this.conversionTaskId = response.data.taskId;
                this.addLog('success', `转换任务已创建，任务ID: ${this.conversionTaskId}`);
                
                // 开始轮询转换进度
                this.pollConversionProgress();
            } else {
                throw new Error(response.data.message || '转换启动失败');
            }

        } catch (error) {
            console.error('转换启动失败:', error);
            let errorMessage = '转换启动失败';
            if (error.response?.data?.message) {
                errorMessage += '：' + error.response.data.message;
            } else if (error.message) {
                errorMessage += '：' + error.message;
            }
            this.addLog('error', errorMessage);
            this.showConversionProgress(false);
        }
    }

    async pollConversionProgress() {
        if (!this.conversionTaskId) return;

        try {
            const response = await axios.get(`/api/dataconversion/progress/${this.conversionTaskId}`);
            
            if (response.data.success) {
                const { status, progress, message, result } = response.data;

                this.updateConversionProgress(progress || 0);
                
                if (message) {
                    this.addLog('info', message);
                }

                if (status === 'completed') {
                    this.showConversionProgress(false);
                    this.addLog('success', '数据转换完成！');
                    this.updateConversionStatus('success', '转换完成');
                    
                    // 更新统计信息
                    if (result && result.stats) {
                        this.updateStats(result.stats);
                    }
                    
                    // 切换到下载步骤
                    setTimeout(() => {
                        this.showStep('download');
                        this.loadDownloadFiles();
                    }, 1000);
                    
                } else if (status === 'failed') {
                    this.showConversionProgress(false);
                    this.addLog('error', '数据转换失败');
                    this.updateConversionStatus('error', '转换失败');
                    
                } else {
                    // 继续轮询
                    setTimeout(() => this.pollConversionProgress(), 2000);
                }
            } else {
                throw new Error(response.data.message || '获取转换进度失败');
            }

        } catch (error) {
            console.error('获取转换进度失败:', error);
            let errorMessage = '获取转换进度失败';
            if (error.response?.data?.message) {
                errorMessage += '：' + error.response.data.message;
            } else if (error.message) {
                errorMessage += '：' + error.message;
            }
            this.addLog('error', errorMessage);
            this.showConversionProgress(false);
        }
    }

    showConversionProgress(show) {
        const progressDiv = document.getElementById('conversion-progress');
        if (show) {
            progressDiv.classList.remove('d-none');
        } else {
            progressDiv.classList.add('d-none');
        }
    }

    updateConversionProgress(progress) {
        const progressBar = document.querySelector('#conversion-progress .progress-bar');
        progressBar.style.width = progress + '%';
    }

    updateConversionStatus(type, message) {
        const statusDiv = document.getElementById('conversion-status');
        statusDiv.className = `alert alert-${type === 'success' ? 'success' : type === 'error' ? 'danger' : 'info'}`;
        statusDiv.innerHTML = `
            <div class="text-center">
                <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-triangle' : 'info-circle'} me-2"></i>
                ${message}
            </div>
        `;
    }

    addLog(type, message) {
        const logsContainer = document.getElementById('conversion-logs');
        const timestamp = new Date().toLocaleTimeString();
        
        // 如果是第一条日志，清空占位内容
        if (logsContainer.querySelector('.text-center')) {
            logsContainer.innerHTML = '';
        }

        const logEntry = document.createElement('div');
        logEntry.className = `log-entry log-${type} mb-2`;
        logEntry.innerHTML = `
            <div class="d-flex align-items-start">
                <span class="log-time text-muted me-2">${timestamp}</span>
                <span class="log-icon me-2">
                    <i class="fas fa-${type === 'success' ? 'check' : type === 'error' ? 'times' : 'info'}"></i>
                </span>
                <span class="log-message flex-grow-1">${message}</span>
            </div>
        `;

        logsContainer.appendChild(logEntry);
        logsContainer.scrollTop = logsContainer.scrollHeight;
    }

    async loadDownloadFiles() {
        if (!this.conversionTaskId) return;

        try {
            // 使用实际的下载文件列表
            const fileName = this.selectedFile ? this.selectedFile.name : '转换结果';
            const nameWithoutExt = fileName.replace(/\.[^/.]+$/, "");
            const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, '');
            
            const files = [
                {
                    name: `${nameWithoutExt}_${dateStr}.xlsx`,
                    type: 'converted',
                    size: '未知',
                    downloadUrl: `/api/download/result/${this.conversionTaskId}/converted`
                }
            ];

            this.renderDownloadFiles(files);

        } catch (error) {
            console.error('加载下载文件失败:', error);
        }
    }

    renderDownloadFiles(files) {
        const container = document.getElementById('download-files');
        
        if (files.length === 0) {
            container.innerHTML = `
                <div class="text-center text-muted py-4">
                    <i class="fas fa-file-alt fa-3x mb-3"></i>
                    <h5>暂无可下载文件</h5>
                </div>
            `;
            return;
        }

        container.innerHTML = files.map(file => `
            <div class="download-file-item mb-3">
                <div class="d-flex align-items-center justify-content-between p-3 border rounded">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-${file.type === 'converted' ? 'file-excel' : 'file-alt'} fa-2x text-primary me-3"></i>
                        <div>
                            <div class="fw-bold">${file.name}</div>
                            <div class="small text-muted">${file.size}</div>
                        </div>
                    </div>
                    <button class="btn btn-primary" onclick="dataProcessing.downloadFile('${file.downloadUrl}', '${file.name}')">
                        <i class="fas fa-download me-2"></i>下载
                    </button>
                </div>
            </div>
        `).join('');
    }

    downloadFile(url, filename) {
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        link.target = '_blank';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        this.addLog('info', `开始下载文件: ${filename}`);
    }

    updateStats(stats) {
        const { successful = 0, failed = 0, total = 0 } = stats;
        const successRate = total > 0 ? Math.round((successful / total) * 100) : 0;

        document.querySelector('#conversion-stats .stat-number.text-success').textContent = successful;
        document.querySelector('#conversion-stats .stat-number.text-danger').textContent = failed;
        document.querySelector('#conversion-stats .stat-number.text-info').textContent = total;
        document.querySelector('#conversion-stats .stat-number.text-warning').textContent = successRate + '%';
    }

    updateConversionInfo() {
        if (this.selectedFile) {
            document.getElementById('uploaded-file-name').textContent = this.selectedFile.name;
        }
        
        const conversionType = document.getElementById('conversionType');
        document.getElementById('selected-conversion-type').textContent = 
            conversionType.options[conversionType.selectedIndex].text;
    }

    showStep(step) {
        // 更新进度指示器
        document.querySelectorAll('.step').forEach(s => s.classList.remove('active', 'completed'));
        
        const steps = ['upload', 'convert', 'download'];
        const currentIndex = steps.indexOf(step);
        
        steps.forEach((s, index) => {
            const stepEl = document.getElementById(`step-${s}`);
            if (index < currentIndex) {
                stepEl.classList.add('completed');
            } else if (index === currentIndex) {
                stepEl.classList.add('active');
            }
        });

        // 显示对应的内容区域
        document.getElementById('upload-section').classList.toggle('d-none', step !== 'upload');
        document.getElementById('conversion-section').classList.toggle('d-none', step !== 'convert');
        document.getElementById('download-section').classList.toggle('d-none', step !== 'download');

        this.currentStep = step;
    }

    backToUpload() {
        this.showStep('upload');
    }

    restartProcess() {
        // 重置所有状态
        this.uploadedFileId = null;
        this.conversionTaskId = null;
        this.selectedFile = null;
        
        // 重置表单
        document.getElementById('conversionType').value = '';
        this.clearFile();
        
        // 清空日志
        document.getElementById('conversion-logs').innerHTML = `
            <div class="text-center text-muted py-5">
                <i class="fas fa-file-alt fa-3x mb-3"></i>
                <h5>转换日志</h5>
                <p>转换过程中的详细信息将在这里显示</p>
            </div>
        `;
        
        // 重置统计
        this.updateStats({ successful: 0, failed: 0, total: 0 });
        
        // 回到第一步
        this.showStep('upload');
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    showAlert(type, message, position = 'top-right') {
        // 创建临时提示框
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show position-fixed`;
        
        // 根据position参数设置位置样式
        if (position === 'center') {
            alertDiv.style.cssText = `
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                z-index: 9999;
                min-width: 350px;
                max-width: 500px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.15);
                border-radius: 8px;
            `;
        } else {
            alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        }
        
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(alertDiv);
        
        // 3秒后自动消失
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.parentNode.removeChild(alertDiv);
            }
        }, 3000);
    }
}

// 全局实例
let dataProcessing;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    dataProcessing = new DataProcessing();
});

// 全局函数供HTML调用
window.clearFile = () => dataProcessing.clearFile();
window.backToUpload = () => dataProcessing.backToUpload();
window.restartProcess = () => dataProcessing.restartProcess();